<template>
  <el-container v-if="isShowMenu">
    <el-header>
      <el-row style="width: 100%;" :gutter="20">
        <el-col :span="22">
          <div class="grid-content ep-bg-purple" />
        </el-col>
        <el-col :span="2" :offset="0">
          <el-dropdown v-if="userName && userName.length > 0" @command="handleCommand">
            <span class="el-dropdown-link">
              <!-- <span> 欢迎你：</span> -->
              {{ userName && userName.length > 0 ? userName : '登录' }}
              <!-- {{ userName }} -->
              <el-icon class="el-icon">
                <arrow-down />
              </el-icon>
            </span>

            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="changePwd">修改密码</el-dropdown-item>
                <!-- <el-dropdown-item command="b" disabled>Action 4</el-dropdown-item> -->
                <el-dropdown-item command="logout" style="color:#c70d0d " divided>退出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="primary" v-else link @click="goLogin">登录</el-button>

        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-active="activeIndex" text-color="#fff" 
        background-color="#000000" v-model:openeds="openKeys">
          <!-- <el-menu default-active="/routeconfig" text-color="#fff" background-color="#000000"> -->
          <NestedMenuItem v-for="item in menuRenders" :key="item.path" :item="item">
          </NestedMenuItem>
        </el-menu>
      </el-aside>
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
  <router-view v-else></router-view>
</template>
<script>
import { useRouter, useRoute } from 'vue-router'
import { ref, provide, computed, watchEffect } from 'vue'
import NestedMenuItem from './components/NestedMenuItem.vue'
import { ArrowDown } from '@element-plus/icons-vue'


import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  name: 'MyMenu',
  components: {
    NestedMenuItem,
  },
  provide() {
    return {
      refreshMenu: this.refreshMenu,
    };
  },
  setup() {
    // var isMenuDataLoad = ref(false)
    const store = useStore()
    var routesConfig = []
    var menuItems = ref([])
    const router = useRouter()
    const route = useRoute()
    var menuRenders = ref([]);
    var activeIndex = ref('')
    var openKeys = ref([])

    store.dispatch('initializeStore')


    var userName = localStorage.getItem('userName')
    console.log('app setup',userName)
    // localStorage.setItem('userId', res.Data.userId)
    // 递归查找所有父级Id
    function findOpenKeys(menuList, currentPath, parentKeys = []) {
      for (const item of menuList) {
        if (item.path === currentPath) {
          return parentKeys
        }
        if (item.children && item.children.length > 0) {
          const found = findOpenKeys(item.children, currentPath, [...parentKeys, item.Id.toString()])
          if (found) return found
        }
      }
      return null
    }
    watchEffect(() => {
      console.log('Current route is: ', route.path);
      activeIndex.value = route.path
      // 计算 openKeys
      openKeys.value = findOpenKeys(menuRenders.value, route.path) || []
      console.log('openKeys', openKeys.value)
    });
    const isShowMenu = computed(() => {
      // route.path
      console.log('store.state.routesConfig', store.state.routesConfig)
      console.log(' route.path', route.path)
      // var findItem=store.state.routesConfig.find(x=>x.path.toLowerCase()==route.path)
      var findItem = store.state.routesConfig.find(x => x.path == route.path)

      console.log('findItem', findItem)
      if (findItem && !findItem.IsLayout) {
        return false
      }

      return true
    });

    // const handleCommand = (command: string | number | object) => {
    //   ElMessage(`click on item ${command}`)
    // }

    const handleCommand = (command) => {
      console.log('aa')
      switch (command) {
        case 'changePwd':
          onChangePwd()
          break;
        case 'logout':
          goLogin()
          break;
      }
    }
    var onChangePwd=()=>{
      console.log('onChangePwd')
      router.push('/ChangePwd')
    }
    var goLogin = () => {
      console.log('goLogin')
      localStorage.removeItem('token')
      ElMessage.success("退出成功")
      //记录登录前页面
      localStorage.setItem('beforeLoginPath', router.currentRoute.value.path)
      router.push('/Login')
    }
    function refreshMenu() {
      // 刷新菜单的逻辑
      store.dispatch('getMenuData').then(() => {
        routesConfig = store.state.routesConfig
        console.log('refreshMenu routesConfig')

        Object.assign(menuItems, routesConfig)
        formatMenuData()

        activeIndex.value = route.path
        if (activeIndex.value == "/") {
          activeIndex.value = "/home"
        }
        router.push(activeIndex.value)
        // isMenuDataLoad.value = true
      })
    }
    // function refreshUserInfo(){
      
    // }
    // provide('refreshUserInfo', refreshUserInfo);
    refreshMenu()
    // 提供刷新菜单的方法
    provide('refreshMenu', refreshMenu);
    const formatMenuData = () => {
      var menus0 = routesConfig.filter(x => x.ParentId == 0)

      var formattedMenus = getMenuChildren(menus0)
      var showMenus = formattedMenus.filter(x => x.IsShow)
      console.log('formattedMenus IsLayout', showMenus)
      menuRenders.value = showMenus
    }

    const getMenuChildren = (menuItems) => {
      menuItems.forEach(item => {
        //添加路由
        router.addRoute(item)
        item.children = routesConfig.filter(x => x.ParentId == item.Id)
        getMenuChildren(item.children)
      })
      return menuItems
    }

    return {
      menuRenders,
      handleCommand,
      goLogin,
      activeIndex,
      refreshMenu,
      router,
      userName,
      isShowMenu,
      route,
      menuItems,
      openKeys
    }
  }
}


</script>


<style>
html,
body {
  height: 100%;
  margin: 0;
}

.el-header {
  background: #232537;
  box-shadow: 4px 2px 4px 1px rgb(61 65 91 / 88%);
  z-index: 3;
  color: white;
  display: flex;
  align-items: center;
}

#app {
  height: 100%;
}

.el-dropdown-link:focus-visible {
  outline: none !important;
}

#app .el-container {
  height: inherit;
}

.el-dropdown {
  cursor: pointer;
  color: white !important;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
}

.el-menu {
  height: 100%;
}

/* Visual polish */
.el-aside {
  background: #1b1e2b;
  border-right: 1px solid #2a2f45;
}

.el-main {
  background: #f5f7fa;
  padding: 16px;
}

/* Keep menu readable on dark aside */
.el-aside .el-menu {
  background-color: transparent;
}

.el-aside .el-menu .el-menu-item.is-active,
.el-aside .el-menu .el-sub-menu.is-active > .el-sub-menu__title {
  background-color: #2a2f45;
}

/* Softer cards */
.el-card {
  border-radius: 8px;
}
</style>